package com.yangrd.airship.sys.web.modules.sys;

import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.StringExpression;
import com.yangrd.airship.common.jpa.BaseController;
import com.yangrd.airship.upms.domain.*;
import com.yangrd.airship.upms.support.AuthorizeDescribe;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer;
import org.springframework.data.querydsl.binding.QuerydslBindings;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.RolesAllowed;
import java.util.Collection;

/**
 * description: UserController
 *
 * @author: yangrd
 * @date: 2021/7/3
 * @version: 1.0
 */
@Api(tags = "系统管理-字典管理")
@AuthorizeDescribe({"系统管理", "字典管理"})
@RequiredArgsConstructor


@RestController
@RequestMapping("/api/sys/dict")
public class DictController extends BaseController<Dict, Integer, DictRepository> {

    @PostMapping("/{id}/items")
    public void addItem(@PathVariable("id") Dict dict, @RequestBody DictItem item){
        dict.addItem(item);
        repository.save(dict);
    }

    @GetMapping("/items")
    public Collection<DictItem> listItem(@RequestParam String keyword){
        return repository.findOne(DictSpec.toSpec(keyword)).map(Dict::getItems).orElseThrow(RuntimeException::new);
    }

    @RolesAllowed("sys:dict:view")
    @GetMapping
    public Page<Dict> findAll(@QuerydslPredicate(root = Dict.class, bindings = DictQueryDslBinderCustomizer.class) Predicate predicate, Pageable pageable) {
        return repository.findAll(predicate, pageable);
    }

    static class DictQueryDslBinderCustomizer implements QuerydslBinderCustomizer<QDict> {

        @Override
        public void customize(QuerydslBindings querydslBindings, QDict qDict) {
            querydslBindings.bind(qDict.name).first(StringExpression::contains);
        }
    }
}
